<template>
  <div class="system-config">
    <el-tabs v-model="activeTab">
      <el-tab-pane :label="$t('system.globalAttendanceRules')" name="attendance">
        <el-card class="box-card">
          <el-form 
            :model="attendanceForm"
            :rules="attendanceRules"
            ref="attendanceForm"
            label-width="120px"
            class="config-form">
            <el-form-item :label="$t('system.semesterTime')" required>
              <el-col :span="11">
                <el-form-item prop="semesterStart">
                  <el-date-picker
                    v-model="attendanceForm.semesterStart"
                    type="date"
                    :placeholder="$t('system.startDate')"
                    value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item prop="semesterEnd">
                  <el-date-picker
                    v-model="attendanceForm.semesterEnd"
                    type="date"
                    :placeholder="$t('system.endDate')"
                    value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('system.defaultCheckInTime')" required>
              <el-col :span="11">
                <el-form-item prop="checkInTime">
                  <el-time-picker
                    v-model="attendanceForm.checkInTime"
                    format="HH:mm"
                    :placeholder="$t('system.startTime')"
                    value-format="HH:mm">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item prop="checkInEndTime">
                  <el-time-picker
                    v-model="attendanceForm.checkInEndTime"
                    format="HH:mm"
                    :placeholder="$t('system.endTime')"
                    value-format="HH:mm">
                  </el-time-picker>
                </el-form-item>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('system.locationRequirement')">
              <el-switch v-model="attendanceForm.locationRequired"></el-switch>
            </el-form-item>

            <el-form-item 
              :label="$t('system.longitude')" 
              v-if="attendanceForm.locationRequired" 
              prop="locationLongitude">
              <el-col :span="11">
                <el-input 
                  v-model="attendanceForm.locationLongitude" 
                  :placeholder="$t('attendance.inputLongitude')">
                </el-input>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="getCurrentLocation"
                  :disabled="loading">
                  {{ $t('system.getLocation') }}
                </el-button>
              </el-col>
            </el-form-item>

            <el-form-item 
              :label="$t('system.latitude')" 
              v-if="attendanceForm.locationRequired" 
              prop="locationLatitude">
              <el-col :span="11">
                <el-input 
                  v-model="attendanceForm.locationLatitude" 
                  :placeholder="$t('attendance.inputLatitude')">
                </el-input>
              </el-col>
            </el-form-item>

            <el-form-item 
              :label="$t('system.validDistance')" 
              v-if="attendanceForm.locationRequired" 
              prop="validDistance">
              <el-input-number 
                v-model="attendanceForm.validDistance" 
                :min="1"
                :max="1000"
                :placeholder="$t('attendance.setValidDistance')">
              </el-input-number>
              <span class="unit">{{ $t('system.meterUnit') }}</span>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitAttendanceForm('attendanceForm')" :loading="loading">
                {{ $t('system.saveSettings') }}
              </el-button>
              <el-button @click="resetAttendanceForm('attendanceForm')" :loading="loading">
                {{ $t('system.resetSettings') }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <el-tab-pane :label="$t('system.leaveTypeManagement')" name="leaveType">
        <el-card class="box-card">
          <div class="operation-bar">
            <el-button type="primary" @click="handleAddType">
              <i class="el-icon-plus"></i> {{ $t('system.addLeaveType') }}
            </el-button>
            <el-input
              v-model="typeQuery.name"
              :placeholder="$t('system.filterLeaveType')"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="handleFilter"
              clearable>
              <el-button slot="append" icon="el-icon-search" @click="handleFilter"></el-button>
            </el-input>
          </div>

          <el-table 
            :data="leaveTypes" 
            style="width: 100%"
            v-loading="loading">
            <el-table-column prop="name" :label="$t('system.leaveTypeName')" min-width="120"></el-table-column>
            <el-table-column prop="description" :label="$t('common.description')" min-width="200"></el-table-column>
            <el-table-column prop="maxDays" :label="$t('system.maxDays')" width="100">
              <template slot-scope="scope">
                {{ scope.row.maxDays || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="sort" :label="$t('system.sort')" width="80"></el-table-column>
            <el-table-column prop="enabled" :label="$t('common.status')" width="80">
              <template slot-scope="scope">
                <el-tag :type="scope.row.enabled ? 'success' : 'info'">
                  {{ scope.row.enabled ? $t('system.enabled') : $t('system.disabled') }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="requireAttachment" :label="$t('system.requireAttachment')" width="120">
              <template slot-scope="scope">
                <el-tag :type="scope.row.requireAttachment ? 'warning' : ''">
                  {{ scope.row.requireAttachment ? $t('system.required') : $t('system.notRequired') }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" :label="$t('common.createdTime')" width="180">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right" v-if="!isMobile">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  @click="handleEditType(scope.row)"
                  :disabled="loading">
                  {{ $t('common.edit') }}
                </el-button>
                <el-button 
                  type="text" 
                  class="danger-text" 
                  @click="handleDeleteType(scope.row)"
                  :disabled="loading">
                  {{ $t('common.delete') }}
                </el-button>
              </template>
            </el-table-column>
            
            <!-- 移动端操作列 -->
            <el-table-column label="操作" width="95" fixed="right" v-if="isMobile">
              <template slot-scope="scope">
                <el-popover
                  placement="left"
                  width="120"
                  trigger="click">
                  <div class="mobile-operation-buttons">
                    <el-button 
                      type="text" 
                      @click="handleEditType(scope.row)"
                      :disabled="loading">
                      {{ $t('common.edit') }}
                    </el-button>
                    <el-button 
                      type="text" 
                      class="danger-text" 
                      @click="handleDeleteType(scope.row)"
                      :disabled="loading">
                      {{ $t('common.delete') }}
                    </el-button>
                  </div>
                  <el-button slot="reference" type="primary" size="mini">
                    {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="typeQuery.current"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="typeQuery.size"
              :layout="paginationLayout"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 请假类型编辑对话框 -->
    <el-dialog 
      :title="typeDialogTitle" 
      :visible.sync="typeDialogVisible" 
      width="500px"
      :fullscreen="isMobile"
      :close-on-click-modal="false"
      @closed="resetTypeForm('typeForm')">
      <el-form 
        :model="typeForm" 
        :rules="typeRules" 
        ref="typeForm" 
        label-width="100px"
        :disabled="loading">
        <el-form-item :label="$t('system.leaveTypeName')" prop="name">
          <el-input v-model="typeForm.name" maxlength="50" show-word-limit></el-input>
        </el-form-item>
        <el-form-item :label="$t('system.leaveTypeDesc')" prop="description">
          <el-input 
            type="textarea" 
            v-model="typeForm.description"
            maxlength="200"
            show-word-limit
            :rows="3">
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('system.maxDays')" prop="maxDays">
          <el-input-number 
            v-model="typeForm.maxDays" 
            :min="1" 
            :max="365"
            controls-position="right">
          </el-input-number>
          <span class="tip">（单次请假最大天数）</span>
        </el-form-item>
        <el-form-item :label="$t('system.sort')" prop="sort">
          <el-input-number 
            v-model="typeForm.sort" 
            :min="0" 
            :max="999"
            controls-position="right">
          </el-input-number>
          <span class="tip">（数字越小越靠前）</span>
        </el-form-item>
        <el-form-item :label="$t('system.enabled')" prop="enabled">
          <el-switch
            v-model="typeForm.enabled"
            active-text="$t('system.enabled')"
            inactive-text="$t('system.disabled')">
          </el-switch>
        </el-form-item>
        <el-form-item :label="$t('system.requireAttachment')" prop="requireAttachment">
          <el-switch
            v-model="typeForm.requireAttachment"
            active-text="$t('system.required')"
            inactive-text="$t('system.notRequired')">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="typeDialogVisible = false" :disabled="loading">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button 
          type="primary" 
          @click="submitTypeForm('typeForm')"
          :loading="loading">
          {{ $t('common.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { parseTime } from '@/utils/index'
import ElementUI from "element-ui";

export default {
  name: 'SystemConfig',
  data() {
    // 验证结束日期大于开始日期
    const validateEndDate = (rule, value, callback) => {
      if (value && this.attendanceForm.semesterStart) {
        if (value < this.attendanceForm.semesterStart) {
          callback(new Error(this.$t('attendance.endDateMustBeGreaterThanStartDate')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    
    // 验证结束时间大于开始时间
    const validateEndTime = (rule, value, callback) => {
      if (value && this.attendanceForm.checkInTime) {
        if (value <= this.attendanceForm.checkInTime) {
          callback(new Error(this.$t('attendance.endTimeMustBeGreaterThanStartTime')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      activeTab: 'attendance',
      loading: false,
      attendanceForm: {
        semesterStart: '',
        semesterEnd: '',
        checkInTime: '',
        checkInEndTime: '',
        locationRequired: false,
        locationLongitude: '',
        locationLatitude: '',
        validDistance: 100
      },
      attendanceRules: {
        semesterStart: [
          { required: true, message: this.$t('attendance.selectSemesterStart'), trigger: 'change' }
        ],
        semesterEnd: [
          { required: true, message: this.$t('attendance.selectSemesterEnd'), trigger: 'change' },
          { validator: validateEndDate, trigger: 'change' }
        ],
        checkInTime: [
          { required: true, message: this.$t('attendance.selectCheckInTime'), trigger: 'change' }
        ],
        checkInEndTime: [
          { required: true, message: this.$t('attendance.selectCheckInEndTime'), trigger: 'change' },
          { validator: validateEndTime, trigger: 'change' }
        ],
        locationLongitude: [
          { required: true, message: this.$t('attendance.inputLongitude'), trigger: 'blur' },
          { pattern: /^[\-\+]?\d+(\.\d+)?$/, message: this.$t('attendance.invalidLongitude'), trigger: 'blur' }
        ],
        locationLatitude: [
          { required: true, message: this.$t('attendance.inputLatitude'), trigger: 'blur' },
          { pattern: /^[\-\+]?\d+(\.\d+)?$/, message: this.$t('attendance.invalidLatitude'), trigger: 'blur' }
        ],
        validDistance: [
          { required: true, message: this.$t('attendance.setValidDistance'), trigger: 'blur' },
          { type: 'number', min: 1, max: 1000, message: this.$t('attendance.distanceBetween1And1000'), trigger: 'blur' }
        ]
      },
      typeQuery: {
        current: 1,
        size: 10,
        name: ''
      },
      leaveTypes: [],
      total: 0,
      typeDialogVisible: false,
      typeDialogTitle: '',
      typeForm: {
        id: null,
        name: '',
        description: '',
        maxDays: 7,
        sort: 0,
        enabled: true,
        requireAttachment: false
      },
      typeRules: {
        name: [
          { required: true, message: this.$t('common.pleaseEnter') + this.$t('system.leaveTypeName'), trigger: 'blur' },
          { min: 2, max: 50, message: this.$t('common.lengthLimit', {min: 2, max: 50}), trigger: 'blur' }
        ],
        description: [
          { max: 200, message: this.$t('common.lengthCannotExceed', {max: 200}), trigger: 'blur' }
        ],
        maxDays: [
          { required: true, message: this.$t('system.setMaxDays'), trigger: 'blur' },
          { type: 'number', min: 1, max: 365, message: this.$t('system.daysBetween1And365'), trigger: 'blur' }
        ],
        sort: [
          { required: true, message: this.$t('common.inputSort'), trigger: 'blur' },
          { type: 'number', message: this.$t('common.sortMustBeNumber'), trigger: 'blur' }
        ]
      },
      isMobile: false,
      screenWidth: document.body.clientWidth,
      paginationLayout: "total, sizes, prev, pager, next, jumper"
    }
  },
  created() {
    this.getGlobalConfig()
    this.getLeaveTypes()
    this.checkScreenSize()
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
    this.checkScreenSize()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth
      this.checkScreenSize()
    },
    checkScreenSize() {
      this.isMobile = this.screenWidth < 768
      
      // 根据屏幕尺寸调整分页控件布局
      if (this.isMobile) {
        this.paginationLayout = "prev, pager, next"
      } else {
        this.paginationLayout = "total, sizes, prev, pager, next, jumper"
      }
    },
    // 获取全局配置
    async getGlobalConfig() {
      try {
        this.loading = true
        const res = await request.get('/attendance/config/global')
        if (res.data) {
          const config = res.data
          //console.log(config)
          this.attendanceForm = {
            semesterStart: config.semesterStart,
            semesterEnd: config.semesterEnd,
            checkInTime: config.checkInTime ? config.checkInTime.substring(0, 5) : '',
            checkInEndTime: config.checkInEndTime ? config.checkInEndTime.substring(0, 5) : '',
            locationRequired: config.locationRequired,
            locationLongitude: config.locationLongitude || '',
            locationLatitude: config.locationLatitude || '',
            validDistance: config.validDistance || 100
          }
        }
      } catch (error) {
        this.$message.error(this.$t('system.loadFailed'))
        console.error('获取全局配置失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 获取请假类型列表
    async getLeaveTypes() {
      try {
        this.loading = true
        const res = await request.get('/leave/types', {
          params: this.typeQuery
        })
        this.leaveTypes = res.data
        //console.log(this.leaveTypes)
        this.total = res.data.total
      } catch (error) {
        this.$message.error(this.$t('system.loadFailed'))
        console.error('获取请假类型失败:', error)
        this.leaveTypes = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const hour = time.hour.toString().padStart(2, '0')
      const minute = time.minute.toString().padStart(2, '0')
      return `${hour}:${minute}`
    },

    // 解析时间
    parseTime(timeStr) {
      if (!timeStr) return null
      const [hour, minute] = timeStr.split(':').map(Number)
      return `${hour}:${minute}`
    },

    // 格式化日期时间
    formatDateTime(time) {
      if (!time) return ''
      return parseTime(time, '{y}-{m}-{d} {h}:{i}')
    },

    // 提交全局考勤配置
    async submitAttendanceForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true
            
            // 确保时间值是字符串格式
            let checkInTime = this.attendanceForm.checkInTime
            let checkInEndTime = this.attendanceForm.checkInEndTime
            
            // 如果是对象，则将其转换为字符串
            if (typeof checkInTime === 'object' && checkInTime !== null) {
              checkInTime = this.formatTime(checkInTime)
            }
            
            if (typeof checkInEndTime === 'object' && checkInEndTime !== null) {
              checkInEndTime = this.formatTime(checkInEndTime)
            }
            
            const config = {
              semesterStart: this.attendanceForm.semesterStart,
              semesterEnd: this.attendanceForm.semesterEnd,
              checkInTime: checkInTime,
              checkInEndTime: checkInEndTime,
              locationRequired: this.attendanceForm.locationRequired,
              locationLongitude: parseFloat(this.attendanceForm.locationLongitude),
              locationLatitude: parseFloat(this.attendanceForm.locationLatitude),
              validDistance: parseInt(this.attendanceForm.validDistance)
            }
            
            await request.post('/attendance/config/global', config)
            this.$message.success(this.$t('system.saveSuccess'))
          } catch (error) {
            this.$message.error(this.$t('system.saveFailed'))
            console.error('保存全局考勤规则失败:', error)
          } finally {
            this.loading = false
          }
        }
      })
    },

    // 重置考勤配置表单
    resetAttendanceForm(formName) {
      this.$refs[formName].resetFields()
      this.getGlobalConfig()
    },

    // 重置请假类型表单
    resetTypeForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
      this.typeForm = {
        id: null,
        name: '',
        description: '',
        maxDays: 7,
        sort: 0,
        enabled: true,
        requireAttachment: false
      }
    },

    // 处理搜索
    handleFilter() {
      this.typeQuery.current = 1
      this.getLeaveTypes()
    },

    // 添加请假类型
    handleAddType() {
      this.typeDialogTitle = this.$t('system.addLeaveType')
      this.resetTypeForm('typeForm')
      this.typeDialogVisible = true
    },

    // 编辑请假类型
    handleEditType(row) {
      this.typeDialogTitle = this.$t('common.edit')
      this.typeForm = {
        id: row.id,
        name: row.name,
        description: row.description,
        maxDays: row.maxDays || 7,
        sort: row.sort || 0,
        enabled: row.enabled !== false,
        requireAttachment: row.requireAttachment || false
      }
      this.typeDialogVisible = true
    },

    // 删除请假类型
    async handleDeleteType(row) {
      try {
        await this.$confirm(this.$t('common.deleteConfirm'), this.$t('common.tip'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        })
        
        this.loading = true
        await request.delete(`/leave/types/${row.id}`)
        this.$message.success(this.$t('common.deleteSuccess'))
        this.getLeaveTypes()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(this.$t('common.deleteFailed'))
          console.error('删除请假类型失败:', error)
        }
      } finally {
        this.loading = false
      }
    },

    // 提交请假类型表单
    async submitTypeForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true
            const data = {
              ...this.typeForm,
              maxDays: parseInt(this.typeForm.maxDays),
              sort: parseInt(this.typeForm.sort)
            }
            if (this.typeForm.id) {
              await request.put('/leave/types/update', data)
            } else {
              await request.post('/leave/types/create', data)
            }
            this.$message.success(this.$t('common.operationSuccess'))
            this.typeDialogVisible = false
            this.getLeaveTypes()
          } catch (error) {
            this.$message.error(this.$t('system.saveFailed'))
            console.error('保存请假类型失败:', error)
          } finally {
            this.loading = false
          }
        }
      })
    },

    // 处理分页大小变化
    handleSizeChange(val) {
      this.typeQuery.size = val
      this.getLeaveTypes()
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.typeQuery.current = val
      this.getLeaveTypes()
    },

    getCurrentLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.attendanceForm.locationLongitude = position.coords.longitude.toFixed(6);
            this.attendanceForm.locationLatitude = position.coords.latitude.toFixed(6);
            ElementUI.Message.success(this.$t('attendance.currentLocation') + ": " + 
              this.attendanceForm.locationLongitude + ", " + this.attendanceForm.locationLatitude);
          },
          (error) => {
            console.error('Error getting location:', error);
            ElementUI.Message.error(this.$t('attendance.locationNotAvailable'));
          }
        );
      } else {
        ElementUI.Message.error(this.$t('attendance.locationNotAvailable'));
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.system-config {
  padding: 20px;
  
  .config-form {
    max-width: 800px;
  }
  
  .line {
    text-align: center;
    line-height: 40px;
  }
  
  .unit {
    margin-left: 10px;
    color: #606266;
  }

  .tip {
    margin-left: 10px;
    color: #909399;
    font-size: 13px;
  }
  
  .operation-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .filter-item {
      margin-left: 10px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .danger-text {
    color: #F56C6C;
  }

  .el-dialog__body {
    padding: 20px;
  }
  
  .mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
  }

  .mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
  }
}

@media screen and (max-width: 768px) {
  .system-config {
    .operation-bar {
      flex-direction: column;
      align-items: flex-start;
      
      .el-button {
        margin-bottom: 10px;
      }
      
      .filter-item {
        margin-left: 0;
        width: 100%;
      }
    }
    
    .el-table {
      width: 100%;
      font-size: 12px;
    }
    
    .el-button {
      padding: 7px 10px;
      font-size: 12px;
    }
    
    .config-form .el-date-editor,
    .config-form .el-time-picker,
    .config-form .el-input,
    .config-form .el-input-number {
      width: 100%;
    }
  }
}
</style> 